package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.ArticleReply;
import com.example.forum.model.User;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/comment/admin")
@Api(tags = "评论管理接口")
@Slf4j
public class CommentAdminController {

    @Resource
    private IArticleReplyService articleReplyService;
    
    @Resource
    private IArticleService articleService;
    
    /**
     * 获取评论列表，支持分页、关键词搜索和状态筛选
     * @param request HTTP请求
     * @param page 页码
     * @param size 每页记录数
     * @param keyword 搜索关键词
     * @param status 状态筛选
     * @return 包含评论列表和分页信息的结果
     */
    @ApiOperation("管理员获取评论列表")
    @GetMapping("/list")
    public AppResult getCommentList(
            HttpServletRequest request,
            @ApiParam("页码") @RequestParam(value = "page", defaultValue = "1") int page,
            @ApiParam("每页条数") @RequestParam(value = "size", defaultValue = "10") int size,
            @ApiParam("搜索关键词") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam("状态筛选") @RequestParam(value = "status", required = false) String status) {
        
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        try {
            // 计算分页参数
            if (page < 1) {
                page = 1;
            }
            if (size < 1) {
                size = 10;
            }
            
            // 调用服务层方法获取评论列表
            List<Map<String, Object>> commentList = articleReplyService.getCommentsByPage(page, size, keyword, status);
            
            // 获取总记录数
            int total = articleReplyService.countCommentsByCondition(keyword, status);
            
            log.info("评论列表查询结果 - 本页数量: {}, 估计总数: {}", commentList.size(), total);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", commentList);
            result.put("total", total);
            
            return AppResult.success(result);
        } catch (Exception e) {
            log.error("获取评论列表失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    /**
     * 删除评论
     * @param request HTTP请求
     * @param id 评论ID
     * @return 操作结果
     */
    @ApiOperation("删除评论")
    @PostMapping("/delete")
    public AppResult deleteComment(
            HttpServletRequest request,
            @ApiParam("评论ID") @RequestBody Map<String, Object> params) {
        
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        try {
            // 获取评论ID
            if (params == null || !params.containsKey("id")) {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论ID不能为空");
            }
            
            Object idObj = params.get("id");
            Long id;
            
            // 解析评论ID
            if (idObj instanceof Integer) {
                id = ((Integer) idObj).longValue();
            } else if (idObj instanceof Long) {
                id = (Long) idObj;
            } else if (idObj instanceof String) {
                try {
                    id = Long.parseLong((String) idObj);
                } catch (NumberFormatException e) {
                    return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论ID格式不正确");
                }
            } else {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论ID格式不正确");
            }
            
            // 检查评论是否存在
            ArticleReply reply = articleReplyService.getById(id);
            if (reply == null || reply.getDeleteState() == 1) {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论不存在或已被删除");
            }
            
            // 执行删除操作
            articleReplyService.adminDeleteComment(id);
            
            return AppResult.success();
        } catch (Exception e) {
            log.error("删除评论失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    /**
     * 忽略所有举报
     * @param request HTTP请求
     * @param params 包含评论ID的参数
     * @return 操作结果
     */
    @ApiOperation("忽略评论举报")
    @PostMapping("/ignoreReports")
    public AppResult ignoreReports(
            HttpServletRequest request,
            @ApiParam("包含评论ID的参数") @RequestBody Map<String, Object> params) {
        
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        try {
            // 获取评论ID
            if (params == null || !params.containsKey("id")) {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论ID不能为空");
            }
            
            Object idObj = params.get("id");
            Long id;
            
            // 解析评论ID
            if (idObj instanceof Integer) {
                id = ((Integer) idObj).longValue();
            } else if (idObj instanceof Long) {
                id = (Long) idObj;
            } else if (idObj instanceof String) {
                try {
                    id = Long.parseLong((String) idObj);
                } catch (NumberFormatException e) {
                    return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论ID格式不正确");
                }
            } else {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论ID格式不正确");
            }
            
            // 检查评论是否存在
            ArticleReply reply = articleReplyService.getById(id);
            if (reply == null || reply.getDeleteState() == 1) {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论不存在或已被删除");
            }
            
            // 执行忽略举报操作
            articleReplyService.ignoreReports(id);
            
            return AppResult.success();
        } catch (Exception e) {
            log.error("忽略评论举报失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    /**
     * 获取评论的举报列表
     * @param request HTTP请求
     * @param id 评论ID
     * @return 评论的举报列表
     */
    @ApiOperation("获取评论举报列表")
    @GetMapping("/getReports")
    public AppResult getReportList(
            HttpServletRequest request,
            @ApiParam("评论ID") @RequestParam("id") Long id) {
        
        // 验证管理员权限
        if (!isAdmin(request)) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        
        try {
            // 检查评论是否存在
            ArticleReply reply = articleReplyService.getById(id);
            if (reply == null || reply.getDeleteState() == 1) {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论不存在或已被删除");
            }
            
            // 获取举报列表
            List<Map<String, Object>> reportList = articleReplyService.getReportListByCommentId(id);
            
            return AppResult.success(reportList);
        } catch (Exception e) {
            log.error("获取评论举报列表失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    /**
     * 检查用户是否是管理员
     * @param request HTTP请求
     * @return 是否是管理员
     */
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return false;
        }
        
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        return user != null && user.getIsAdmin() == 1;
    }
}
